package com.gome.boot.config.elasticsearch.standalone;

import com.gome.boot.config.elasticsearch.BaseElasticsearchConfig;
import com.gome.boot.config.elasticsearch.cluster.ClusterClient;
import com.gome.boot.config.elasticsearch.cluster.MultiClusterClient;
import org.elasticsearch.client.Client;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.context.annotation.Bean;
import org.springframework.data.elasticsearch.core.ElasticsearchTemplate;

/**
 * ES服务基础配置.
 * <br/>单集群或单实例模式.
 *
 * @author baoxiufeng
 */
public class BaseStandaloneElasticsearchConfig extends BaseElasticsearchConfig {

    @Bean(name = "clusterClient")
    @ConditionalOnMissingBean
    public ClusterClient clusterClient() throws Exception {
        String clusterName = env.getRequiredProperty(KEY_ES_CLUSTER_NAME);
        String clusterNodes = env.getRequiredProperty(KEY_ES_CLUSTER_NOES);
        return new ClusterClient(createClient(clusterName, clusterNodes), clusterName);
    }

    @Bean(name = "multiClient")
    @ConditionalOnMissingBean
    public MultiClusterClient multiClient(@Qualifier("clusterClient") ClusterClient clusterClient) {
        MultiClusterClient multiClient = MultiClusterClient.getInstance();
        multiClient.addClient(clusterClient);
        multiClient.setMultiple(false);
        return multiClient;
    }

    @Bean
    @ConditionalOnMissingBean
    public Client client(@Qualifier("clusterClient") ClusterClient clusterClient) {
        return clusterClient.getClient();
    }

    @Bean
    @ConditionalOnMissingBean
    public ElasticsearchTemplate elasticsearchTemplate(@Qualifier("clusterClient") ClusterClient clusterClient) {
        return clusterClient.getTemplate();
    }
}
